/**
 * 图片压缩工具的主要JavaScript文件
 * 实现图片上传、压缩和下载功能
 */

// DOM元素引用
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const uploadArea = document.getElementById('upload-area');
const compressionArea = document.getElementById('compression-area');
const originalImage = document.getElementById('original-image');
const compressedImage = document.getElementById('compressed-image');
const originalDimensions = document.getElementById('original-dimensions');
const originalSize = document.getElementById('original-size');
const compressedDimensions = document.getElementById('compressed-dimensions');
const compressedSize = document.getElementById('compressed-size');
const sizeReduction = document.getElementById('size-reduction');
const qualitySlider = document.getElementById('quality-slider');
const qualityValue = document.getElementById('quality-value');
const maxWidthInput = document.getElementById('max-width');
const formatSelect = document.getElementById('format-select');
const compressBtn = document.getElementById('compress-btn');
const downloadBtn = document.getElementById('download-btn');
const resetBtn = document.getElementById('reset-btn');
const uploadButton = document.querySelector('.upload-button'); // 添加上传按钮引用

// 全局变量
let originalFile = null;
let compressedBlob = null;

/**
 * 初始化事件监听器
 */
function initEventListeners() {
    // 拖拽相关事件
    dropZone.addEventListener('dragover', handleDragOver);
    dropZone.addEventListener('dragleave', handleDragLeave);
    dropZone.addEventListener('drop', handleDrop);
    // 修改点击事件监听方式
    dropZone.addEventListener('click', function(e) {
        // 防止事件冒泡导致重复触发
        if (e.target === uploadButton || uploadButton.contains(e.target)) {
            // 如果点击的是上传按钮，让fileInput.click()在事件处理中执行
            return;
        }
        fileInput.click();
    });
    
    // 确保上传按钮直接绑定事件
    uploadButton.addEventListener('click', function(e) {
        e.stopPropagation(); // 阻止事件冒泡
        fileInput.click();
    });
    
    // 文件选择事件
    fileInput.addEventListener('change', handleFileSelect);
    
    // 控制按钮事件
    compressBtn.addEventListener('click', compressImage);
    downloadBtn.addEventListener('click', downloadImage);
    resetBtn.addEventListener('click', resetUI);
    
    // 实时更新质量显示和滑块进度
    qualitySlider.addEventListener('input', () => {
        qualityValue.textContent = `${qualitySlider.value}%`;
        updateSliderProgress(qualitySlider);
    });
    
    // 初始化滑块进度
    createSliderProgress();
    updateSliderProgress(qualitySlider);
}

/**
 * 为滑块创建进度条元素
 */
function createSliderProgress() {
    // 检查是否已存在进度条元素
    if (!document.querySelector('.slider-progress')) {
        const progressElement = document.createElement('div');
        progressElement.className = 'slider-progress';
        // 插入到滑块之前
        qualitySlider.parentNode.insertBefore(progressElement, qualitySlider);
        // 确保滑块和进度条正确叠放
        qualitySlider.style.position = 'relative';
        qualitySlider.style.zIndex = '1';
    }
}

/**
 * 更新滑块进度条显示
 * @param {HTMLInputElement} slider - 滑块元素
 */
function updateSliderProgress(slider) {
    const progress = document.querySelector('.slider-progress');
    if (progress) {
        const percent = (slider.value - slider.min) / (slider.max - slider.min) * 100;
        progress.style.width = `${percent}%`;
    }
}

/**
 * 处理拖拽经过事件
 * @param {DragEvent} event - 拖拽事件对象
 */
function handleDragOver(event) {
    event.preventDefault();
    event.stopPropagation();
    dropZone.classList.add('drag-over');
}

/**
 * 处理拖拽离开事件
 * @param {DragEvent} event - 拖拽事件对象
 */
function handleDragLeave(event) {
    event.preventDefault();
    event.stopPropagation();
    dropZone.classList.remove('drag-over');
}

/**
 * 处理文件拖放事件
 * @param {DragEvent} event - 拖拽事件对象
 */
function handleDrop(event) {
    event.preventDefault();
    event.stopPropagation();
    dropZone.classList.remove('drag-over');
    
    const files = event.dataTransfer.files;
    if (files.length) {
        processFile(files[0]);
    }
}

/**
 * 处理文件选择事件
 * @param {Event} event - 文件选择事件对象
 */
function handleFileSelect(event) {
    const files = event.target.files;
    if (files.length) {
        processFile(files[0]);
    }
}

/**
 * 处理选择的文件
 * @param {File} file - 用户选择的文件对象
 */
function processFile(file) {
    // 验证文件类型
    const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!validTypes.includes(file.type)) {
        alert('请选择有效的图片文件 (JPG, PNG, WEBP)');
        return;
    }
    
    // 验证文件大小 (最大10MB)
    if (file.size > 10 * 1024 * 1024) {
        alert('文件大小不能超过10MB');
        return;
    }
    
    // 保存原始文件引用
    originalFile = file;
    
    // 显示文件信息
    originalSize.textContent = formatFileSize(file.size);
    
    // 加载并显示原始图片
    const reader = new FileReader();
    reader.onload = function(e) {
        originalImage.src = e.target.result;
        
        // 图片加载完成后获取尺寸
        originalImage.onload = function() {
            originalDimensions.textContent = `${originalImage.naturalWidth} x ${originalImage.naturalHeight}`;
            
            // 设置最大宽度输入框的默认值
            maxWidthInput.placeholder = originalImage.naturalWidth.toString();
            
            // 显示压缩区域
            uploadArea.style.display = 'none';
            compressionArea.style.display = 'block';
        };
    };
    reader.readAsDataURL(file);
}

/**
 * 压缩图片
 */
function compressImage() {
    if (!originalFile) return;
    
    const quality = parseInt(qualitySlider.value) / 100;
    const maxWidth = maxWidthInput.value ? parseInt(maxWidthInput.value) : null;
    const format = formatSelect.value;
    
    // 创建离屏Canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    // 计算新尺寸
    let newWidth = originalImage.naturalWidth;
    let newHeight = originalImage.naturalHeight;
    
    if (maxWidth && maxWidth < newWidth) {
        const ratio = maxWidth / newWidth;
        newWidth = maxWidth;
        newHeight = Math.round(newHeight * ratio);
    }
    
    // 设置Canvas尺寸
    canvas.width = newWidth;
    canvas.height = newHeight;
    
    // 绘制图像
    ctx.drawImage(originalImage, 0, 0, newWidth, newHeight);
    
    // 转换为Blob
    canvas.toBlob(
        (blob) => {
            if (!blob) {
                alert('压缩失败，请重试');
                return;
            }
            
            compressedBlob = blob;
            
            // 更新压缩后的信息
            compressedSize.textContent = formatFileSize(blob.size);
            compressedDimensions.textContent = `${newWidth} x ${newHeight}`;
            
            // 计算节省比例
            const reduction = ((originalFile.size - blob.size) / originalFile.size * 100).toFixed(2);
            sizeReduction.textContent = `${reduction}%`;
            
            // 显示压缩后的图片
            const url = URL.createObjectURL(blob);
            compressedImage.src = url;
            
            // 启用下载按钮
            downloadBtn.disabled = false;
        },
        format === 'jpeg' ? 'image/jpeg' : 
        format === 'png' ? 'image/png' : 'image/webp',
        quality
    );
}

/**
 * 下载压缩后的图片
 */
function downloadImage() {
    if (!compressedBlob) return;
    
    const format = formatSelect.value;
    const extension = format === 'jpeg' ? 'jpg' : format;
    
    // 创建文件名
    const originalName = originalFile.name.split('.')[0];
    const fileName = `${originalName}_compressed.${extension}`;
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(compressedBlob);
    link.download = fileName;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * 重置UI回到初始状态
 */
function resetUI() {
    // 清除图片和数据
    originalImage.src = '';
    compressedImage.src = '';
    originalFile = null;
    compressedBlob = null;
    
    // 重置显示的信息
    originalDimensions.textContent = '0 x 0';
    originalSize.textContent = '0 KB';
    compressedDimensions.textContent = '0 x 0';
    compressedSize.textContent = '0 KB';
    sizeReduction.textContent = '0%';
    
    // 重置控制元素
    qualitySlider.value = 80;
    qualityValue.textContent = '80%';
    maxWidthInput.value = '';
    formatSelect.value = 'jpeg';
    downloadBtn.disabled = true;
    
    // 显示上传区域，隐藏压缩区域
    uploadArea.style.display = 'block';
    compressionArea.style.display = 'none';
    
    // 清空文件输入
    fileInput.value = '';
}

/**
 * 格式化文件大小显示
 * @param {number} bytes - 文件大小（字节）
 * @returns {string} 格式化后的文件大小
 */
function formatFileSize(bytes) {
    if (bytes < 1024) {
        return bytes + ' B';
    } else if (bytes < 1024 * 1024) {
        return (bytes / 1024).toFixed(2) + ' KB';
    } else {
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initEventListeners); 